package com.ias.log.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

// import com.ias.common.constant.TraceConstant;

/**
 * @author owen
 * 首先创建拦截器，加入拦截列表中，在请求到达时生成traceId。
 * blog: https://blog.51cto.com/13005375 
 * code: https://gitee.com/owenwangwen/open-capacity-platform
 * 
 * 注意：此类依赖 TraceConstant 常量类，如果项目中没有该类，请自行定义或使用默认值
 */
public class LogInterceptor implements HandlerInterceptor {
    
    // 如果没有 TraceConstant 类，使用默认值
    private static final String HTTP_HEADER_TRACE_ID = "x-traceId";
    private static final String LOG_TRACE_ID = "traceId";
    
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // "traceId"
       
        String traceId = request.getHeader(HTTP_HEADER_TRACE_ID);
        if (StringUtils.isNotEmpty(traceId)) {
        	 MDC.put(LOG_TRACE_ID, traceId);
        }

        return true;
    }
}
